package cn.com.csg.smartenergy.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用于订阅EMQ客户端上下线的回调
 * 上线主题：$SYS/brokers/+/CLIENTS/+/connected
 * 下线主题：$SYS/brokers/+/CLIENTS/+/disconnected
 *
 * @author ysguo
 * @date 2019-09-11
 */
@Slf4j
@Component
public class DeviceOnlineCallBack extends AbstractCallBack {

    @Autowired
    private DeviceOnlineHandler onlineHandler;

    /**
     * 消息接收回调方法
     *
     * @param topic 主题
     * @param message 消息
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        System.out.println("收到消息：" + message.toString());
        // 此处必须要有 try catch 报异常会自动关闭mqtt客户端
        try {
            this.onlineHandler.handleOnlineMessage(topic, message, this.getClient());
        } catch (Exception e) {
            log.error(String.format("处理设备上报数据出现异常：Topic: %s", topic), e);
        }
    }

}
